package com.rongshu.view.mediaPlayer.activity;

import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rongshu.R;
import com.rongshu.eventbus.PostComment;
import com.rongshu.eventbus.UpdatePlayUI;
import com.rongshu.utils.Constant;
import com.rongshu.utils.ControlScrollLayoutManager;
import com.rongshu.utils.DateUtils;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.adapter.CommentAdapter;
import com.rongshu.view.home.entity.CommentDetails;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.home.fragment.dialog.InputNoteDialog;
import com.rongshu.view.home.listener.OnItemFunctionClickListener;
import com.rongshu.view.home.widget.favor.FavorLayout;
import com.rongshu.view.mediaPlayer.bean.AudiobookDetailsResponse;
import com.rongshu.view.mediaPlayer.bean.PlayEvent;
import com.rongshu.view.mediaPlayer.emnu.MediaState;
import com.rongshu.view.mediaPlayer.emnu.PlayAction;
import com.rongshu.view.mediaPlayer.iview.AudiobookPlayerView;
import com.rongshu.view.mediaPlayer.listener.AudiobookPlayListener;
import com.rongshu.view.mediaPlayer.manager.PlayerManager;
import com.rongshu.view.mediaPlayer.presenter.AudiobookPlayingPresenter;
import com.rongshu.view.mediaPlayer.service.PlayerService;
import com.rongshu.view.userInfo.activity.PersonDetailsActivity;
import com.rongshu.widget.MusicPlayImage;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utils.FastClickUtils;
import com.widget.dialog.BottomListDialog;
import com.widget.titlebar.ImmersionBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

import static com.rongshu.utils.UserInfoUtils.getUserId;

/**
 * created by zhengweis on 2019/4/22.
 * description：有声文章播放页面
 */
public class AudiobookPlayerActivity extends BaseActivity<AudiobookPlayingPresenter> implements
        AudiobookPlayerView, OnItemFunctionClickListener, AudiobookPlayListener {
    @BindView(R.id.layout_parent)
    RelativeLayout layout_parent;
    @BindView(R.id.comment_list)
    RecyclerView commentList;
    @BindView(R.id.praise_img)
    ImageView praiseImg;
    @BindView(R.id.praise_num)
    TextView praiseNum;
    @BindView(R.id.comment_num)
    TextView commentNum;
    @BindView(R.id.right_option)
    LinearLayout rightOption;
    @BindView(R.id.media_start)
    ImageView mediaStart;
    @BindView(R.id.media_progress)
    SeekBar mediaProgress;
    @BindView(R.id.scroll_view)
    NestedScrollView scrollView;
    @BindView(R.id.comment_layout)
    RelativeLayout commentLayout;
    @BindView(R.id.progress_current)
    TextView progressCurrent;
    @BindView(R.id.progress_total)
    TextView progressTotal;
    @BindView(R.id.refresh_view)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.view_stub_empty)
    ViewStub empty;
    @BindView(R.id.audiobook_cover)
    MusicPlayImage audiobookCover;
    @BindView(R.id.audiobook_title)
    TextView audiobookTitle;
    @BindView(R.id.audiobook_author)
    TextView audiobookAuthor;
    @BindView(R.id.audiobook_reader)
    TextView audiobookReader;
    @BindView(R.id.audiobook_intro)
    TextView audiobookIntro;
    @BindView(R.id.audiobook_editor)
    TextView audiobookEditor;
    @BindView(R.id.audiobook_time)
    TextView audiobookTime;
    @BindView(R.id.collect_iv)
    ImageView collectIv;
    @BindView(R.id.head_content)
    RelativeLayout headContent;
    @BindView(R.id.round_iv)
    ImageView round_iv;

    //播放事件
    private PlayEvent playEvent;
    //音频总时长
    private int mediaDuration;
    //音频当前播放时长
    private int mediaCurrentPositon;
    //一级评论每页展示数量
    private int pageIndex = 1;
    private int pageSize = 10;
    //二级评论回复每页展示数量
    private int replyPageIndex = 1;
    private int replyPageSize = 100;
    //评论的缺省页面
    private View inflate;
    private RelativeLayout layoutEmpty;
    //评论列表
    private List<CommentDetails.ResponseBean> comments;
    //评论适配器
    private CommentAdapter adapter = null;
    //评论ID,回复ID
    private int comment_id = 0, reply_id = 0;
    //local_position 局部刷新position
    private int local_position;
    //是否删除回复
    private boolean isDeteleReply = false;
    //评论回复的position
    private int replyPosition = 0;
    //标记点赞的item
    private int praisePosition;
    //有声文章详情实体类
    private AudiobookDetailsResponse.ResponseBean bean;
    //layout_top_menu 高度
    private int top_menu_height = 0;
    //layout_top_menu 进入退出动画
    private ObjectAnimator topEnterAnimation, topExitAnimation;
    //头部是否隐藏
    private boolean topIsHide = false;
    //音频是否正在缓冲
    private boolean mediaIsPrepare = false;
    private Handler handler;
    private int audioId;

    //是否手动点赞
    private boolean isManualLike = false;
    //点赞爱心
    private FavorLayout favorLayout = null;
    //点赞提示语
    private List<String> likeTips = null;
    //dialog
    private InputNoteDialog inputNoteDialog = null;
    //内容
    private String mContent = "";
    //提示
    private String mReplyContent = null;
    //@的用戶信息
    private LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap = null;
    //isScrollToBottom
    private boolean isScrollToBottom = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar bar = ImmersionBar.with(this);
        bar.with(this).keyboardEnable(false,
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
                .init();
        if (ImmersionBar.isSupportStatusBarDarkFont()) {//是否支持修改状态栏字体颜色
            bar.statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.color_2c2c2c)  //修改flyme OS状态栏字体颜色
                    .init();  //必须调用方可沉浸式
        } else {
            bar.flymeOSStatusBarFontColor(R.color.black)  //修改flyme OS状态栏字体颜色
                    //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                    .statusBarDarkFont(true, 1.0f)
                    .init();  //必须调用方可沉浸式
        }
        bar.init();
        EventBus.getDefault().register(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, PlayerService.class));
        } else {
            startService(new Intent(this, PlayerService.class));
        }
        handler = new Handler();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_media_player;
    }

    @Override
    protected void initView() {
        setPresenter(new AudiobookPlayingPresenter(this), this);
        audioId = getIntent().getIntExtra(Constant.INTENT_DATA, 0);
        smartRefreshLayout.setHeaderHeight(0);
        smartRefreshLayout.setEnableRefresh(false);
        smartRefreshLayout.setEnableHeaderTranslationContent(false);
        smartRefreshLayout.setEnableAutoLoadmore(false);
        //list
        likeTips = Arrays.asList(new String[]{
                getString(R.string.its_nice_to_be_liked),
                getString(R.string.received_your_like_thank_you),
                getString(R.string.once_thumb_up_very_close),
                getString(R.string.warm_praise_reliable_shoulder),
                getString(R.string.thanks_for_your_encouragement)});
        //manager
        ControlScrollLayoutManager manager = new ControlScrollLayoutManager(this);
        manager.setScrollEnabled(false);
        comments = new ArrayList<>();
        //adapter
        adapter = new CommentAdapter(this);
        adapter.setResponseBeanList(comments);
        adapter.setHasStableIds(true);
        adapter.setOnItemFunctionClickListener(this);
        //recyclerview
        commentList.setLayoutManager(manager);
        commentList.setAdapter(adapter);
        //@list
        authorDetailBeanMap = new LinkedHashMap<>();
        getViewHeight();
        //爱心
        favorLayout = new FavorLayout(this);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelOffset(R.dimen.dd_dimen_700px));
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        lp.bottomMargin = getResources().getDimensionPixelOffset(R.dimen.dd_dimen_32px);
        lp.leftMargin = getResources().getDimensionPixelOffset(R.dimen.dd_dimen_210px);
        favorLayout.setLayoutParams(lp);
        layout_parent.addView(favorLayout);
    }

    @Override
    protected void initData() {
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageIndex = 1;
                refreshlayout.resetNoMoreData();
                presenter.getAudiobookComment(bean.getId(), pageIndex, pageSize);
            }
        });
        smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex++;
                presenter.getAudiobookComment(bean.getId(), pageIndex, pageSize);
            }
        });
        mediaProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaDuration != 0) {
                    int progress = seekBar.getProgress();
                    PlayerManager.getPlayer().seekTo(progress * 1000);
                }
            }
        });
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > oldScrollY) {//向下滚动
                    if (!topIsHide) {
                        showHideTopAnimation();
                    }
                }
                if (scrollY < oldScrollY) {//向上滚动
                    if (topIsHide) {
                        showHideTopAnimation();
                    }
                }
            }
        });
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getAudiobookDetails(audioId);
        application.hideFloatWindow();
    }

    /**
     * 更新 当前播放时间，总播放时间，seekbar
     */
    private void updatePlayProgress() {
        //当前播放时长
        mediaCurrentPositon = PlayerManager.getPlayer().getCurrentPosition();
        //音频总时长
        mediaDuration = PlayerManager.getPlayer().getDuration();
        //设置播放时长
        if (PlayerManager.getPlayer().getMediaState() == MediaState.COMPLETED) {
            progressCurrent.setText(bean.getMin());
        } else {
            progressCurrent.setText(presenter.timeFormat(mediaCurrentPositon + 1000));
        }
        //设置总时长
        progressTotal.setText(bean.getMin());
        //设置进度条最大值
        mediaProgress.setMax(mediaDuration / 1000);
        //设置当前进度
        mediaProgress.setProgress(mediaCurrentPositon / 1000);
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 1000);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (PlayerManager.getPlayer().isPlaying()) {
                //更新 当前播放时间，seekbar
                mediaCurrentPositon = PlayerManager.getPlayer().getCurrentPosition();
                progressCurrent.setText(presenter.timeFormat(mediaCurrentPositon + 1000));
                mediaProgress.setProgress(mediaCurrentPositon / 1000);
                handler.postDelayed(runnable, 1000);
            }
        }
    };

    @OnClick({R.id.head_left, R.id.head_right, R.id.media_start, R.id.praise_layout,
            R.id.comment_option, R.id.share_layout, R.id.comment_content})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_left:
                onBackPressed();
                break;
            case R.id.head_right:
                if (UserInfoUtils.getUserInfo() == null) {
                    LoginUtils.toLogin(this);
                } else if (!FastClickUtils.isFastClick()) {
                    presenter.collectionAudiobook(bean.getId());
                }
                break;
            case R.id.media_start:
                if (bean == null || TextUtils.isEmpty(bean.getMp3Url())) {
                    toast("音频文件异常，检查网络是否连接");
                    return;
                }
                if (PlayerManager.getPlayer().getDuration() <= 0
                        || PlayerManager.getPlayer().getMediaState() == MediaState.COMPLETED) {
                    presenter.activeReplay(application.getUserPhoneNetwork(), playEvent);
                    return;
                }
                audiobookCover.playMusic();
                if (PlayerManager.getPlayer().isPlaying()) {
                    playEvent.setAction(PlayAction.PAUST);
                    EventBus.getDefault().post(playEvent);
                    Glide.with(this).load(R.drawable.media_pause_icon).into(mediaStart);
                } else {
                    playEvent.setAction(PlayAction.PLAY);
                    EventBus.getDefault().post(playEvent);
                    Glide.with(this).load(R.drawable.media_start_icon).into(mediaStart);
                    updatePlayProgress();
                }
                break;
            case R.id.praise_layout:
                if (bean == null) {
                    return;
                }
                if (UserInfoUtils.getUserInfo() != null) {
                    //用户数据不为空，用户未点过赞
                    if (bean.getIsLike() == 0) {
                        isManualLike = true;
                        presenter.getLike(bean.getId());
                    } else {
                        presenter.getOffLike(bean.getId());
                    }
                } else {
                    LoginUtils.toLogin(this);
                }
                break;
            case R.id.comment_option:
                if (isScrollToBottom) {
                    scrollView.smoothScrollTo(0, 0);
                    isScrollToBottom = false;
                } else {
                    int top = commentLayout.getTop();
                    scrollView.smoothScrollTo(0, top);
                    isScrollToBottom = true;
                }
                break;
            case R.id.share_layout:
                if (bean == null) {
                    return;
                }
                presenter.share(bean.getId());
                break;
            case R.id.comment_content:
                if (UserInfoUtils.getUserInfo() == null) {
                    LoginUtils.toLogin(this);
                }
                getInputDialog().show(getSupportFragmentManager(), InputNoteDialog.class.getSimpleName());
                break;
        }
    }

    /**
     * 显示输入框弹窗
     */
    private InputNoteDialog getInputDialog() {
        inputNoteDialog = InputNoteDialog.getInstance(mContent, mReplyContent, authorDetailBeanMap);
        inputNoteDialog
                .setOnDialogInputListener(new InputNoteDialog.OnDialogInputListener() {
                    @Override
                    public void sendCommentSuccess(LinkedHashMap<String, AuthorDetailBean> map, String content) {
                        presenter.audiobookPostCommentOrReplyAdd(authorDetailBeanMap, Uri.encode(content, "utf-8"), bean.getId(), comment_id, reply_id);
                    }

                    @Override
                    public void dimiss(LinkedHashMap<String, AuthorDetailBean> map, String content, String replyContent) {
                        inputNoteDialog.dismissDialog();
                        inputNoteDialog = null;
                        authorDetailBeanMap = map;
                        mContent = content;
                        mReplyContent = replyContent;
                    }
                });
        return inputNoteDialog;
    }

    //接收EventBus传过来的播放事件
    @Subscribe
    public void onEvent(PlayEvent playEvent) {
        switch (playEvent.getAction()) {
            case PAUST:
                Glide.with(this).load(R.drawable.media_pause_icon).into(mediaStart);
                break;
            case STOP:
            case OVER:
                audiobookCover.resetMusic();
                progressCurrent.setText("00:00");
                mediaProgress.setProgress(0);
                Glide.with(this).load(R.drawable.media_pause_icon).into(mediaStart);
                handler.removeCallbacks(runnable);
                break;
        }
    }

    //音频焦点变换
    @Subscribe
    public void mediaFocusChange(UpdatePlayUI updatePlayUI) {
        audiobookCover.playMusic();
        switch (updatePlayUI.getState()) {
            case AudioManager.AUDIOFOCUS_LOSS:
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                Glide.with(this).load(R.drawable.media_pause_icon).into(mediaStart);
                handler.removeCallbacks(runnable);
                break;
            case AudioManager.AUDIOFOCUS_GAIN:
                Glide.with(this).load(R.drawable.media_start_icon).into(mediaStart);
                break;
        }
    }


    @Override
    public void finishThisAct() {
        if (bean != null) {
            AudiobookDetailsResponse.ResponseBean nowPlaying = PlayerManager.getPlayer().getNowPlaying();
            //getDuration() != 0音频已缓冲完成
            if (nowPlaying != null) {
                application.showFloatWindow();
                application.updateFloatWindowCover(nowPlaying.getTopImg());
                application.updateFloatWindow(true);
            }
            if (mediaIsPrepare) {//正在缓冲此音频，且音频未缓冲完成，需释放播放
                playEvent.setAction(PlayAction.RELEASE);
                EventBus.getDefault().post(playEvent);
            }
        }
        Intent intent = new Intent();
        intent.putExtra(Constant.INTENT_DATA, bean);
        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }

    @Override
    public void onBackPressed() {
        String msg = "";
        if (TextUtils.isEmpty(msg)) {
            finishThisAct();
        } else {
            presenter.exitHint();
        }
    }

    @Override
    protected void onDestroy() {
        audiobookCover.stopMusic();
        super.onDestroy();
        PlayerManager.getPlayer().clearListener();
        EventBus.getDefault().unregister(this);
        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 接口返回文章详情
     */
    @Override
    public void onAudiobookDetails(AudiobookDetailsResponse.ResponseBean response) {
        this.bean = response;
        audiobookCover.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_stroke_gray_background));
        round_iv.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_stroke_gray_background));
        Glide.with(this).load(bean.getTopImg()).into(audiobookCover);
        audiobookTitle.setText(bean.getTitle());
        audiobookAuthor.setText("作者：" + bean.getAuthorName());
        String explain = TextUtils.isEmpty(bean.getZhuBoExplain()) ? "" : " (" + bean.getZhuBoExplain() + ")";
        audiobookReader.setText("主播：" + bean.getZhuBoName() + explain);
        audiobookIntro.setText(bean.getIntro());
        audiobookEditor.setText("责任编辑：" + bean.getRedactName());
        if (!TextUtils.isEmpty(bean.getDailyDate())) {
            audiobookTime.setText(DateUtils.ConvertDate(bean.getDailyDate()));
        }
        collectIv.setBackgroundResource(bean.getIsCollect() == 0 ? R.drawable.top_gray_uncatalog : R.drawable.top_green_catalog);
        praiseImg.setBackgroundResource(bean.getIsLike() == 0 ? R.drawable.love_gray_smasll_icon : R.drawable.love_red_small_icon);
        praiseNum.setText(String.valueOf(bean.getLikeCount()));
        commentNum.setText(String.valueOf(bean.getCommentCount()));
        //请求文章评论
        presenter.getAudiobookComment(bean.getId(), pageIndex, pageSize);
        PlayerManager.getPlayer().setPlayListener(this);
        playEvent = new PlayEvent();
        playEvent.setBean(bean);
        AudiobookDetailsResponse.ResponseBean nowPlaying = PlayerManager.getPlayer().getNowPlaying();
        if (PlayerManager.getPlayer().isPlaying()) {//正在播放
            if (nowPlaying.getId() != bean.getId()) {
                presenter.checkNetState(application.getUserPhoneNetwork(), playEvent);
            } else {
                if (audiobookCover.getState() != MusicPlayImage.STATE_PLAYING) {
                    audiobookCover.playMusic();
                }
                Glide.with(this).load(R.drawable.media_start_icon).into(mediaStart);
                updatePlayProgress();
            }
        } else {
            if (PlayerManager.getPlayer().getDuration() <= 0 || nowPlaying.getId() != bean.getId()) {
                presenter.checkNetState(application.getUserPhoneNetwork(), playEvent);
            } else {
                updatePlayProgress();
            }
        }
    }

    /**
     * 接口返回文章评论列表
     */
    @Override
    public void onCommentMsg(List<CommentDetails.ResponseBean> responseBeanList) {
        if (pageIndex == 1) {
            comments.clear();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadmore();
        }
        comments.addAll(responseBeanList);
        adapter.notifyDataSetChanged();
        if (comments.size() < pageSize) {
            smartRefreshLayout.setLoadmoreFinished(true);
        }
        if (comments.size() == 0) {
            showEmptyLayout();
        } else {
            hideEmptyLayout();
        }
    }

    /**
     * 接口返回单个评论的回复列表
     */
    @Override
    public void onOnecommentDetail(List<CommentReplysBean> commentReplysBeans) {
        adapter.getResponseBeanList().get(local_position).setComment_replys(commentReplysBeans);
        adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
    }

    /**
     * 评论点赞/取消点赞成功
     */
    @Override
    public void onCommentlike() {
        List<CommentDetails.ResponseBean> responseBeanList = adapter.getResponseBeanList();
        if (responseBeanList != null) {
            int likeCount = responseBeanList.get(praisePosition).getLikeCount();
            responseBeanList.get(praisePosition).setLikeCount(likeCount + 1);
            responseBeanList.get(praisePosition).setIslike(1);
            adapter.notifyItemRangeChanged(praisePosition, 1, adapter.GIVELIKE);
        }
    }

    /**
     * 发送评论、回复成功
     *
     * @param body 单条评论、回复
     */
    @Override
    public void commentSuccess(ResponseBody body) {
        toast("评论成功");
        try {
            String json = body.string().toString();
            JSONObject object = new JSONObject(json);
            int errCode = object.getInt("ErrCode");
            String errMsg = object.getString("ErrMsg");
            String respose = object.getString("Response");
            if (errCode == 0) {
                if (comment_id == 0) {//文章评论
                    CommentDetails details = new Gson().fromJson(json, CommentDetails.class);
                    List<CommentDetails.ResponseBean> beanList = details.getResponse();
                    if (beanList != null && !beanList.isEmpty()) {
                        //本地追加评论
                        CommentDetails.ResponseBean bean = beanList.get(0);
                        //原先评论
                        List<CommentDetails.ResponseBean> beans = new ArrayList<>();
                        beans.addAll(comments);
                        //显示评论区，隐藏
                        hideEmptyLayout();
                        //清空集合，填充新数据
                        comments.clear();
                        comments.add(bean);
                        if (!beans.isEmpty()) {
                            comments.addAll(beans);
                        }
                        adapter.notifyDataSetChanged();
                    }
                    //如果评论增加，则评论数需要增加1
                    if (bean == null) {
                        return;
                    }
                    int count = bean.getCommentCount();
                    count = count + 1;
                    bean.setCommentCount(count);
                    commentNum.setText(String.valueOf(bean.getCommentCount()));
                } else {//评论回复，以及回复的回复
                    List<CommentReplysBean> replysBeans = new Gson().fromJson(respose, new TypeToken<List<CommentReplysBean>>() {
                    }.getType());
                    if (replysBeans != null && !replysBeans.isEmpty()) {
                        //原先的评论回复
                        if (comments != null && !comments.isEmpty()) {
                            List<CommentReplysBean> list = new ArrayList<>();
                            CommentDetails.ResponseBean bean = comments.get(local_position);
                            List<CommentReplysBean> replys = bean.getComment_replys();
                            //重新填充一个集合
                            list.addAll(replys);
                            replys.clear();
                            replys.add(replysBeans.get(0));
                            if (!list.isEmpty()) {
                                //添加以前的数据
                                replys.addAll(list);
                            }
                            //此时，comment_replyCount数量需要增加1
                            int count = bean.getComment_replyCount();
                            count = count + 1;
                            bean.setComment_replyCount(count);
                            adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
                        }
                    }
                }
                clean();
            } else {
                toast(errMsg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除评论、回复成功
     */
    @Override
    public void onCommentDelete(INetBean iNetBean) {
        if (iNetBean.getErrCode() == 0) {
            List<CommentDetails.ResponseBean> responseBeans = adapter.getResponseBeanList();
            if (isDeteleReply) {//回复评论
                CommentDetails.ResponseBean response = responseBeans.get(local_position);
                List<CommentReplysBean> replysBeans = response.getComment_replys();
                replysBeans.remove(replyPosition);
                int comment_replyCount = response.getComment_replyCount();
                if (comment_replyCount > 0) {
                    comment_replyCount = comment_replyCount - 1;
                    response.setComment_replyCount(comment_replyCount);
                }
                //如果此时集合中数据和comment_replyCount数据不一致，说明二者数据不一致，需要重新请求
                int replyCount = replysBeans.size();
                if (replyCount < comment_replyCount) {
                    adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
                    presenter.getOnecommentDetail(comment_id, replyPageIndex, replyPageSize);//(此处问题在于，如果获取不到数据，当前一条没有更新view)
                } else {
                    adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
                }
            } else {//回复文章
                responseBeans.remove(local_position);
                adapter.notifyItemRemoved(local_position);
                adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
                //如果评论删除，则评论数需要减去1
                if (bean != null) {
                    int count = bean.getCommentCount();
                    count = count <= 0 ? 0 : count - 1;
                    bean.setCommentCount(count);
                    commentNum.setText(String.valueOf(bean.getCommentCount()));
                }
            }
            int itemCount = adapter.getItemCount();
            if (itemCount == 0) {
                showEmptyLayout();
            } else {
                hideEmptyLayout();
            }
        } else {
            toast(iNetBean.getErrMsg());
        }
        showKeyboard(false);
        clean();
    }

    /**
     * 文章点赞成功
     */
    @Override
    public void onPraiseSuccess() {
        if (bean != null) {
            bean.setIsLike(bean.getIsLike() == 0 ? 1 : 0);
            praiseImg.setBackgroundResource(bean.getIsLike() == 0 ? R.drawable.love_gray_smasll_icon : R.drawable.love_red_small_icon);
            if (bean.getIsLike() == 1 && isManualLike) {
                isManualLike = false;
                favorLayout.addFavor();
                toast(likeTips.get(new Random().nextInt(likeTips.size())));
            }
            int praise = Integer.valueOf(praiseNum.getText().toString().trim());
            if (bean.getIsLike() == 0) {
                praise--;
            } else {
                praise++;
            }
            praiseNum.setText(praise + "");
            bean.setLikeCount(praise);
        }
    }

    /**
     * 文章收藏成功
     */
    @Override
    public void onCollectSuccess() {
        if (bean != null) {
            bean.setIsCollect(bean.getIsCollect() == 0 ? 1 : 0);
            toast(bean.getIsCollect() == 1 ? "已收藏，可至个人中心查看我收藏的" : "取消收藏成功");
            collectIv.setBackgroundResource(bean.getIsCollect() == 0 ? R.drawable.top_gray_uncatalog : R.drawable.top_green_catalog);
        }
    }

    private void clean() {
        inputNoteDialog.dismissDialog();
        local_position = 0;
        isDeteleReply = false;
        replyPosition = 0;
        comment_id = 0;
        reply_id = 0;
    }

    /**
     * 复制，回复，删除评论dialog
     */
    private void showCopyReplyDeleteDialog(final String contents, final String bi_name, final int c_id, final int r_id, int from_uid) {
        if (adapter == null) {
            return;
        }
        //复制，回复，删除
        final List<String> functions = new ArrayList<>();
        functions.add("复制");
        functions.add("回复");
        //当前登录id
        int user_id = UserInfoUtils.getUserId();
        //如果(1.登录id==文章的用户id,则是自己的文章，可以删除)(2.如果来自from_uid==登录id，可以删除)
        if (user_id == from_uid) {
            functions.add("删除");
        }
        BottomListDialog.Builder builder = new BottomListDialog.Builder(this);
        builder.setFunctions(functions)
                .setCancle(getString(R.string.cancle))
                .setCancle_color(R.color.color_2c2c2c)
                .setOption_color(R.color.color_2c2c2c)
                .setOnItemClickListener(new BottomListDialog.Builder.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, Dialog dialog) {
                        dialog.dismiss();
                        String funtion = functions.get(position);
                        if (funtion.equals("复制")) {
                            ClipboardManager mCM = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                            mCM.setPrimaryClip(ClipData.newPlainText(null, contents));
                            toast("复制成功");
                        } else if (funtion.equals("回复")) {
                            comment_id = c_id;
                            reply_id = r_id;
                            mReplyContent = "回复：" + bi_name;
                            getInputDialog().show(getSupportFragmentManager(), InputNoteDialog.class.getSimpleName());
                        } else if (funtion.equals("删除")) {
                            comment_id = c_id;
                            reply_id = r_id;
                            presenter.deleteCommentDeleteDialog(bean.getId(), comment_id, reply_id);
                        }
                    }
                }).create().show();
    }

    @Override
    public void onItemClickListener(int position, String contents, String bi_name, int comment_id, int from_uid) {
        this.local_position = position;
        this.isDeteleReply = false;
        showCopyReplyDeleteDialog(contents, bi_name, comment_id, 0, from_uid);
    }

    @Override
    public void onItemChildClickListener(int position, int replyPosition, String contents, String bi_name, int comment_id, int reply_id, int reply_user_id) {
        this.local_position = position;
        this.replyPosition = replyPosition;
        this.isDeteleReply = true;
        showCopyReplyDeleteDialog(contents, bi_name, comment_id, reply_id, reply_user_id);
    }

    @Override
    public void onItemExpandClickListener(boolean isExpanded, int pageSize, int comment_id, int local_position) {
        if (isExpanded) {
            this.isDeteleReply = false;
            this.local_position = local_position;
            presenter.getOnecommentDetail(comment_id, replyPageIndex, replyPageSize);
        } else {
            if (adapter != null) {
                adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
            }
        }
    }

    @Override
    public void onItemHeaderClickListener(int userid, boolean is_allow_browse_homepage) {
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        Intent intent = null;
        if (user_id == userid) {
            intent = new Intent(this, PersonDetailsActivity.class);
        } else {
            intent = new Intent(this, UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, userid);
        }
        startActivity(intent);
    }

    @Override
    public void onItemGiveLikeClickListener(int comment_id, int position) {
        praisePosition = position;
        // ==0 接口记录未点赞， ==-1本地记录未点赞
        if (UserInfoUtils.getUserInfo() != null) {
            presenter.getCommentlike(bean.getId(), comment_id);
        } else {
            LoginUtils.toLogin(this);
        }
    }

    /**
     * 头部显示动画
     */
    public void showHideTopAnimation() {
        if (!topIsHide) {
            //top进入动画未停止，取消动画
            if (topEnterAnimation.isRunning()) {
                topEnterAnimation.cancel();
            }
            topExitAnimation.start();
            topIsHide = true;
        } else {
            //top退出动画未停止，取消动画
            if (topExitAnimation.isRunning()) {
                topExitAnimation.cancel();
            }
            topEnterAnimation.start();
            topIsHide = false;
        }
    }

    /**
     * 获取view的高度
     */
    private void getViewHeight() {
        ViewTreeObserver topMenuViewTreeObserver = headContent.getViewTreeObserver();
        topMenuViewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                headContent.getViewTreeObserver().removeOnPreDrawListener(this);
                top_menu_height = headContent.getHeight();
                //退出动画
                topExitAnimation = ObjectAnimator.ofFloat(headContent, "translationY", 0, -top_menu_height);
                topExitAnimation.setInterpolator(new LinearInterpolator());
                topExitAnimation.setDuration(300);
                //进入动画
                topEnterAnimation = ObjectAnimator.ofFloat(headContent, "translationY", -top_menu_height, 0);
                topEnterAnimation.setInterpolator(new LinearInterpolator());
                topEnterAnimation.setDuration(300);
                return true;
            }
        });
    }

    /**
     * 显示缺省页面
     */
    private void showEmptyLayout() {
        if (inflate == null) {
            inflate = empty.inflate();
            layoutEmpty = inflate.findViewById(R.id.layout_empty);
            ImageView noDataImg = inflate.findViewById(R.id.no_data_img);
            TextView noDataHint = inflate.findViewById(R.id.no_data_hint);
            noDataImg.setImageResource(R.drawable.empty_comment_bg);
            noDataHint.setText(getString(R.string.comment_empty_hint));
        }
        layoutEmpty.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏缺省页面
     */
    private void hideEmptyLayout() {
        if (layoutEmpty != null) {
            layoutEmpty.setVisibility(View.GONE);
        }
    }

    /**
     * 音频缓冲准备阶段
     */
    @Override
    public void mediaPrepare() {
        mediaIsPrepare = true;
        showLoading(true);
    }

    /**
     * 音频缓冲完成
     */
    @Override
    public void mediaReady() {
        mediaIsPrepare = false;
        showLoading(false);
        if (audiobookCover.getState() != MusicPlayImage.STATE_PLAYING) {
            audiobookCover.playMusic();
        }
        updatePlayProgress();
        Glide.with(AudiobookPlayerActivity.this).load(R.drawable.media_start_icon).into(mediaStart);
    }
}